/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.braveo.dict;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 *
 * @author Yongjie
 */
public class ConfigManager {
    private String currDirectory;
    private static final String CONFIG_DIR = "etc";
    private static final String CONFIG_FILE = "etc/config.xml";

    private static ConfigManager instance;

    public static synchronized ConfigManager getInstance(){
        if(instance == null)
            instance = new ConfigManager();
        return instance;
    }

    private ConfigManager(){
    }

    private void loadConfig(){
        File file = new File(CONFIG_FILE);
        if(!file.exists())
            return;

        FileInputStream is = null;
        Properties p = new Properties();

        try{
            is = new FileInputStream(file);
            p.loadFromXML(is);
        }catch(IOException ioe){
            throw new RuntimeException(ioe);
        }finally{
            if(is!=null){
                try{
                    is.close();
                }catch(IOException ioe){

                }
            }
        }

        this.currDirectory = p.getProperty("com.braveo.dict.CurrDirectory");
    }

    private void saveConfig(){
        File file = new File(CONFIG_DIR);
        if(!file.exists()){
            file.mkdirs();
        }

        file = new File(CONFIG_FILE);
        Properties p = new Properties();
        p.setProperty("com.braveo.dict.CurrDirectory", currDirectory);

        FileOutputStream fos = null;

        try{
            fos = new FileOutputStream(CONFIG_FILE);
            p.storeToXML(fos, "Configuration of Program");
        }catch(IOException ioe){
            throw new RuntimeException(ioe);
        }finally{
            if(fos!=null){
                try{
                    fos.close();

                }catch(IOException ioe){
                    
                }
            }
        }
    }

    public String getCurrDirectory() {
        loadConfig();
        return currDirectory;
    }

    public void setCurrDirectory(String currDirectory) {
        this.currDirectory = currDirectory;
        saveConfig();
    }



}
